package spittr.web;

import static org.springframework.web.bind.annotation.RequestMethod.*;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.Part;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import spittr.Spitter;
import spittr.data.SpitterRepository;

@Controller
@RequestMapping("/spitter")
public class SpitterController {

  private SpitterRepository spitterRepository;

  @Autowired
  public SpitterController(SpitterRepository spitterRepository) {
    this.spitterRepository = spitterRepository;
  }
  
  @RequestMapping(value="/register", method=GET)
  public String showRegistrationForm(Model model) {
    model.addAttribute(new Spitter());
    return "registerForm";
  }

  /**
   * 1.演示通过MultipartFile接收multipart图片数据（注意需要在WebConfig中开启StandardServletMultipartResolver或CommonsMultipartResolver）
   * 2.演示通过在model中添加属性的方式重定向传参
   */
  @RequestMapping(value="/register", method=POST)
  public String processRegistration1(
      @Valid SpitterForm spitterForm,
      Errors errors,Model model) throws IllegalStateException, IOException {
    
    if (errors.hasErrors()) {
      return "registerForm";
    }
    Spitter spitter = spitterForm.toSpitter();
    spitter.setId(UUID.randomUUID().toString());
    spitterRepository.save(spitter);
    MultipartFile profilePicture = spitterForm.getProfilePicture();
    profilePicture.transferTo(new File("E:/uploads/img/" + spitter.getUsername() + ".jpg"));

    //给重定向的url传参，username会填充到{username}，而id会以参数的形式追加到url后面
    //最终结果如：http://localhost:8090/spitter/luobiao?id=a187eedc-c66d-418d-a529-096b5e13ac9f
    model.addAttribute("username", spitter.getUsername());
    model.addAttribute("id", spitter.getId());
    return "redirect:/spitter/{username}";
  }


  /**
   * 1.演示通过Part接收multipart图片数据（主要需要在SpitterWebInitializer中重载customizeRegistration执行setMultipartConfig）
   * 2.演示通过redirectAttributes.addFlashAttribute(spitter)为重定向传参
   */
  @RequestMapping(value="/register", method=POST)
  public String processRegistration2(
          @RequestPart(value="profilePicture", required=false) Part fileBytes,
          RedirectAttributes redirectAttributes,
          @Valid Spitter spitter,
          Errors errors) throws IOException {
    if (errors.hasErrors()) {
      return "registerForm";
    }
    spitter.setId(UUID.randomUUID().toString());
    spitterRepository.save(spitter);
    fileBytes.write("E:/uploads/img/" + spitter.getUsername() + ".jpg");

    //被重定向的Model 中能取到spitter对象
    redirectAttributes.addFlashAttribute(spitter);
    return "redirect:/spitter/" + spitter.getUsername();
  }

  
  @RequestMapping(value="/{username}", method=GET)
  public String showSpitterProfile(
          @PathVariable String username, Model model) {
    if (!model.containsAttribute("spitter")) {
      model.addAttribute(
          spitterRepository.findByUsername(username));
    }
    return "profile";
  }
  
}
